package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.fishingwithme.android.data.model.Auditor
import com.fishingwithme.android.data.model.AuditRequestDto
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class AuditViewModel @Inject constructor(
    private val repository: FishingRepository
) : ViewModel() {
    
    fun getAuditors(approved: Boolean): Flow<PagingData<Auditor>> {
        return Pager(
            config = PagingConfig(
                pageSize = 20,
                enablePlaceholders = false
            ),
            pagingSourceFactory = {
                AuditPagingSource(repository, approved)
            }
        ).flow.cachedIn(viewModelScope)
    }
    
    fun auditSpot(
        bizId: Long,
        ruleItemId: Long,
        reason: String,
        state: Boolean,
        channels: List<String>,
        onSuccess: () -> Unit,
        onError: (String) -> Unit
    ) {
        viewModelScope.launch {
            val auditRequest = AuditRequestDto(
                bizId = bizId,
                ruleItemId = ruleItemId,
                reason = reason,
                state = state,
                channels = channels
            )
            
            repository.auditSpot(auditRequest).collect { result ->
                if (result.isSuccess) {
                    onSuccess()
                } else {
                    onError(result.exceptionOrNull()?.message ?: "Unknown error")
                }
            }
        }
    }
    
    fun auditHarvest(
        bizId: Long,
        ruleItemId: Long,
        reason: String,
        state: Boolean,
        channels: List<String>,
        onSuccess: () -> Unit,
        onError: (String) -> Unit
    ) {
        viewModelScope.launch {
            val auditRequest = AuditRequestDto(
                bizId = bizId,
                ruleItemId = ruleItemId,
                reason = reason,
                state = state,
                channels = channels
            )
            
            repository.auditHarvest(auditRequest).collect { result ->
                if (result.isSuccess) {
                    onSuccess()
                } else {
                    onError(result.exceptionOrNull()?.message ?: "Unknown error")
                }
            }
        }
    }
}